// cloudfunctions/addToCart/index.js
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  console.log('addToCart function invoked with event:', event)
  
  const { userId, productId, model, quantity } = event

  // 参数验证
  if (!userId || !productId || !model || !quantity) {
    console.log('Missing required parameters:', { userId, productId, model, quantity })
    return {
      success: false,
      message: '缺少必要的参数，请重新尝试。'
    }
  }

  if (quantity <= 0) {
    console.log('Invalid quantity:', quantity)
    return {
      success: false,
      message: '购买数量必须大于0。'
    }
  }

  try {
    // 检查商品是否存在
    const productRes = await db.collection('products').doc(productId).get()
    if (!productRes.data) {
      console.log('Product not found:', productId)
      return {
        success: false,
        message: '商品不存在。'
      }
    }

    const product = productRes.data

    // 检查库存
    if (quantity > product.stock) {
      console.log(`Insufficient stock for product ${productId}. Requested: ${quantity}, Available: ${product.stock}`)
      return {
        success: false,
        message: `商品 "${product.name}" 库存不足。`
      }
    }

    // 检查用户的购物车是否已存在该商品和型号
    const cartRes = await db.collection('carts').where({
      userId: userId,
      productId: productId,
      model: model
    }).get()

    if (cartRes.data.length > 0) {
      // 已存在，更新数量
      await db.collection('carts').doc(cartRes.data[0]._id).update({
        data: {
          quantity: _.inc(quantity),
          updatedAt: new Date()
        }
      })
      console.log('Updated existing cart item:', cartRes.data[0]._id)
      return {
        success: true,
        message: '购物车已更新。'
      }
    } else {
      // 不存在，添加新商品到购物车
      await db.collection('carts').add({
        data: {
          userId: userId,
          productId: productId,
          model: model,
          quantity: quantity,
          addedAt: new Date(),
          updatedAt: new Date()
        }
      })
      console.log('Added new item to cart.')
      return {
        success: true,
        message: '商品已加入购物车。'
      }
    }
  } catch (err) {
    console.error('addToCart function error:', err)
    // 根据错误类型返回不同的消息
    if (err.code === 'DATABASE_ERROR') { // 假设 'DATABASE_ERROR' 是数据库操作错误
      return {
        success: false,
        message: '数据库操作失败，请稍后重试。'
      }
    }
    return {
      success: false,
      message: '加入购物车过程中发生错误，请稍后重试。',
      error: err
    }
  }
}
